package com.iwhalecloud.uncc.config;

import com.alibaba.ttl.threadpool.TtlExecutors;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.concurrent.ScheduledExecutorService;

/**
 * @author zq
 * @date 2021/10/18 12:53
 * @description 后置处理taskScheduler线程池 使用TTL包装 (TransmittableThreadLocal　在taskScheduler才起作用)
 */
@Component
@Slf4j
public class ArchiverBeanPostProcessor implements BeanPostProcessor {

    private static final String TASK_SCHEDULER = "taskScheduler";

    @SneakyThrows
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(TASK_SCHEDULER.equals(beanName)){
            Class<?> targetCls = bean.getClass();
            //获取scheduledExecutor属性
            Field f = targetCls.getDeclaredField("scheduledExecutor");
            //设置访问
            f.setAccessible(true);
            //获取getScheduledExecutor方法
            Method m = targetCls.getDeclaredMethod("getScheduledExecutor");
            //执行getScheduledExecutor方法得到ScheduledExecutorService
            ScheduledExecutorService scheduledExecutorService = (ScheduledExecutorService)m.invoke(bean);
            //TTL 设置TTL后的线程池
            f.set(bean,TtlExecutors.getTtlScheduledExecutorService(scheduledExecutorService));
            log.info("taskScheduler TTL 包装成功！");
        }
        return bean;
    }
}
